package cn.wj.school.cloud.security.interceptor;

import cn.wj.school.cloud.security.SecurityContextHolder;
import cn.wj.school.cloud.security.context.SecurityContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author: yueding
 * @Description: 自定义登录拦截器
 * @Date: Created in 10:53 2018/5/17
 * @Modified By: mvc拦截器添加 Copyright(c) cai-inc.com
 */
@Slf4j
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpSession session = request.getSession(false);
        if (session == null) {
            log.debug("ACCESS_LOG[][][]web-session-auth[]用户认证[]认证拦截[]会话不存在");
            return true;
        }
        SecurityContext context = (SecurityContext) session.getAttribute(SecurityContextHolder.SECURITY_CONTEXT);
        // 设置ManagementContext
        if (context != null && context.getAuthentication() != null) {
            SecurityContextHolder.setContext(context);
        } else {
            log.debug("ACCESS_LOG[][][]web-auth[]用户认证[]认证拦截[]未登录[]{}");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SecurityContextHolder.clearContext();
    }
}
